// 1. 引入组合式Api defineStore
import { defineStore } from 'pinia'

import type { CategoryStore } from '@/api/product/model/categoryModel'
//引入接口函数
import {
  reqGetCategory1ListData,
  reqGetCategory2ListData,
  reqGetCategory3ListData,
} from '@/api/product/category'

// 2.创建实例对象
export const useCategoryListStore = defineStore('categoryList', {
  state: (): CategoryStore => {
    return {
      // 以下三个属性用于收集用户真正选择的分类的id
      category1Id: undefined,
      category2Id: undefined,
      category3Id: undefined,

      // 以下三个数组用于存储服务器响应回来的分类数据
      category1List: [],
      category2List: [],
      category3List: [],
    }
  },
  actions: {
    // 1.获取一级分类数据
    async getCategory1ListData() {
      const result = await reqGetCategory1ListData()
      // console.log('pp',result)
      this.category1List = result
    },
    //2. 获取二级分类数据的函数
    async getCategory2ListData(category1Id: number) {
      this.category1Id = category1Id

      // 如果一级导航变了，二三级需要进行重置 也就是需要将id置为undefined
      this.category2Id = undefined
      this.category3Id = undefined
      this.category3List = [] // 将三级列表也要清空

      // 然后再去发送请求 获取二级数据...
      // console.log('我正在根据一级ID获取二级分类数据...')
      this.category2List = await reqGetCategory2ListData(category1Id)
    },
    // 3. 获取三级导航分类数据
    async getCategory3ListData(category2Id: number) {
      this.category2Id = category2Id

      // 将三级数据重置
      this.category3Id = undefined

      // 发送请求获取三级分类数据
      this.category3List = await reqGetCategory3ListData(category2Id)
    },
    // 4.设置三级导航的值
    setCategory3Id(category3Id: number) {
      this.category3Id = category3Id
    },
  },
  getters: {}, //这个就像是计算属性
})
